package com.rayboo.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import com.rayboo.service.AuthUserDetailsService;


/**
 * 
 * @author ray
 *
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	@Autowired
    private WebAuthenticationProvider provider;
    
	@Autowired
    private AuthUserDetailsService authUserDetailsService;
	
	@Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
        	.authorizeRequests()
        	.antMatchers("/logout").permitAll()//退出登录
        	.antMatchers("/css/**","/img/**","/js/**","/data/**").permitAll()//静态资源
        	.anyRequest().authenticated()//all others request authentication
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .defaultSuccessUrl("/users")
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {

    	//将验证过程交给自定义验证工具
    	auth.authenticationProvider(provider);
        auth.userDetailsService(authUserDetailsService).passwordEncoder(new Md5PasswordEncoder());
        
        auth.inMemoryAuthentication()
        	.withUser("test")
            .password("test")
            .roles("USER")
            .and()
            .withUser("admin")
            .password("admin")
            .roles("USER")
            .and()
            .withUser("rayboo")
            .password("rayboo")
            .roles("ADMIN");
    }
    
}